package com.ww.springboot.boot.algorithm.leetcode1;

/**
 * todo
 *
 * @author wanwei
 * @since 2022-03-14 16:36
 */
public class AO64最小路径和 {

    public static void main(String[] args) {

        int[][] grid = {{1,3,1},{1,5,1},{4,2,1}};

        int m = grid.length;
        int n = grid[0].length;
        if(m ==1 && n== 1){
            System.out.println(grid[0][0]);
            return;
        }
        int[][] dp = new int[m][n];
//        for (int i = 0; i <m; i++) {
//            for (int j = 0; j <n; j++) {
//                Integer total = minPathSum(grid, i, j, dp);
//                dp[i][j] = total;
//            }
//        }
        System.out.println(minPathSum(grid, m-1, n-1, dp));
        PrintUtil.print(dp);
    }


    /**
     * 递推
     * <p>
     * F(m,n) = F(m-1,n) + (m-1,n) F(m,n-1) + (m,n-1) 中间较小的那个
     *
     * @param grid
     * @return
     */
    public static int minPathSum(int[][] grid, int m, int n, int[][] dp) {
        Integer total;
        int result = dp[m][n];
        if (result != 0) {
            return result;
        }
        if(m ==0 && n ==0){
            total = 0;
        }else if (m == 0 && n == 1 || m == 1 && n == 0) {
            total = grid[0][0];
        } else if (m == 0) {
            total = minPathSum(grid, 0, n - 1, dp);
        } else if (n == 0) {
            total = minPathSum(grid, m - 1, 0, dp);
        } else {
            total = Math.min(minPathSum(grid, m - 1, n, dp) ,
                    minPathSum(grid, m, n - 1, dp));
        }
        total += grid[m][n];
        dp[m][n] = total;
        return total;
    }


    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int rows = grid.length, columns = grid[0].length;
        int[][] dp = new int[rows][columns];
        dp[0][0] = grid[0][0];
        for (int i = 1; i < rows; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }
        for (int j = 1; j < columns; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < columns; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[rows - 1][columns - 1];
    }

}
